package types

import (
	"net"
	"sync"
)

// ListenerPool 所有监听对象
type ListenerPool struct {
	m sync.Map
}

func (c *ListenerPool) Load(commId string) (listener net.Listener, ok bool) {
	load, ok := c.m.Load(commId)

	if ok {
		listener = load.(net.Listener)
	} else {
		listener = nil
	}

	return
}

func (c *ListenerPool) Store(commId string, listener net.Listener) {
	c.m.Store(commId, listener)
}

func (c *ListenerPool) LoadOrStore(commId string, listener net.Listener) (actual net.Listener, loaded bool) {
	store, loaded := c.m.LoadOrStore(commId, listener)

	if store != nil {
		actual = store.(net.Listener)
	}

	return
}

func (c *ListenerPool) Delete(commId string) {
	c.m.Delete(commId)
}

func (c *ListenerPool) Range(f func(commId string, listener net.Listener) bool) {
	f1 := func(key, value interface{}) bool {
		return f(key.(string), value.(net.Listener))
	}
	c.m.Range(f1)
}
